package com.simple.util.api.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.Configuration;

import java.util.Date;

/**
 * @program: simple_tools
 * @description: 七牛云文件上传的工具类
 * @author: ChenWenLong
 * @create: 2019-12-30 15:53
 **/
public class QiniuUploadUtil {

    private static final String ACCESS_KEY = "注册七牛云后的accesskey";
    private static final String SECRET_KEY = "注册七牛云后的secretKey";
    private static final String BUCKET = "创建的bucket名称";
    // url前缀
    private static final String PRIX = "http://pkbivgfrm.bkt.clouddn.com/";
    private static UploadManager manager;

    public QiniuUploadUtil() {
        //初始化基本配置
        Configuration cfg = new Configuration(Zone.zone0());
        //创建上传管理器
        manager = new UploadManager(cfg);
    }

    //文件名 = key
    //文件的byte数组
    /**
     * 功能描述:
     * 〈上传文件〉
     *
     * @params : [imgName, bytes]
     * @return : java.lang.String
     * @author : cwl
     * @date : 2019/12/30 15:57
     */
    public static String upload(String imgName , byte [] bytes) {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //构造覆盖上传token
        String upToken = auth.uploadToken(BUCKET,imgName);
        try {
            Response response = manager.put(bytes, imgName, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //返回请求地址
            return PRIX+putRet.key+"?t="+new Date().getTime();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
